﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using eCRAM.Model;
using eCRAM.WebSite.Tools;

namespace eCRAM.WebSite.Attributes
{
    public class CustomAuthorizationAttribute : AuthorizeAttribute
    {

        /// <summary>
        /// Nom du controlleur en cours d'acces
        /// </summary>
        string _ctrlName;
        /// <summary>
        /// Stocke si l'utilisateur à le droit d'afficher la page
        /// </summary>
        bool _allowed = false;
        /// <summary>
        /// Stocke si l'utilisateur est connecté
        /// </summary>
        private bool _authenticated;
        /// <summary>
        /// Droit requis pour afficher  l'action
        /// </summary>
        private readonly UserRole[] _prerequisitesRoles;

        public CustomAuthorizationAttribute(params UserRole[] prerequisitesRoles)
        {
            _prerequisitesRoles = prerequisitesRoles;
        }


        /// <summary>
        /// Calcule si l'utilisateur à le droit d'afficher la page
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var currentUser = SessionTools.User;
            _authenticated = currentUser != null;
            if(!_authenticated)
            {
                return false;
            }

            _allowed = _prerequisitesRoles.Contains((UserRole)currentUser.Role);
            return _allowed;
        }

        /// <summary>
        /// Redirige vers une page d'erreur en cas de non authentification
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // On recupere le nom du controller
            _ctrlName = GetControllerName(filterContext.Controller.ToString());
            base.OnAuthorization(filterContext);

            if(!_authenticated)
            {
                var routeDictionary = new RouteValueDictionary();
                routeDictionary.Add("action", "LogOn");
                routeDictionary.Add("controller", "Account");

                 filterContext.Result = new RedirectToRouteResult(routeDictionary);

                //filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new  {View = "LogOn", Controller = "Account"}));
                return;
            }

            // Si il n'a pas les droits => redirection vers une page d'erreur
            if (!_allowed)
            {
                filterContext.Result = new ViewResult() { ViewName = "ErrorAuthentication" };
                return;
            }
        }

        /// <summary>
        /// Recupere le nom du controller
        /// </summary>
        /// <param name="CtrlName"></param>
        /// <returns></returns>
        private string GetControllerName(string CtrlName)
        {
            if (string.IsNullOrEmpty(CtrlName))
            {
                return "Home";
            }
            var tab = CtrlName.Split('.');
            return tab[tab.Length - 1].Replace("Controller", "");
        }
    }
}